package com.sl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sl.entity.Result;
import com.sl.entity.StatusCode;
import com.sl.pojo.User;
import com.sl.service.UserService;
import javafx.scene.input.DataFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sl")
public class LoginController {
    /**
     * 用户名验证
     */
    public static boolean checkName(String name) {
        String regExp = "^[^0-9][\\w_]{5,9}$";
        if(name.matches(regExp)) {
            return true;
        }else {
            return false;
        }
    }
    /**
     * 密码验证
     */
    public static boolean checkPwd(String pwd) {
        String regExp = "^[\\w_]{6,20}$";
        if(pwd.matches(regExp)) {
            return true;
        }
        return false;
    }
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(@RequestBody String data, HttpServletRequest request, HttpServletResponse response) {
        log.info("调用登录接口开始");
        JSONObject jsonObject = JSONObject.parseObject(data);
        String username =jsonObject.get("username").toString();
        String password = jsonObject.get("password").toString();
        log.info("入参解析:" + username + "密码：" + password);

        String sessionId = request.getSession().getId();
        log.info("sessionId:" + sessionId);
        request.getSession().setMaxInactiveInterval(60*60);//没有交互的一小时断开
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || null == username || null == password) {
            throw new RuntimeException("参数为空");
        }
        Subject currentUser = SecurityUtils.getSubject();
        //如果  用户  没登陆。
        if (!currentUser.isAuthenticated()) {
            //用户名和密码封装为UsernamePasswordToken
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //rememberme和isAuthed只能用一个
            //token.setRememberMe(true);
            try {
                User byUsername = userService.findByUsername(username);
                //查不到 不可以登陆
                if (null == byUsername ) {
                    throw new RuntimeException("没有用户信息");
                } else {
                    log.info("获取用户:" + JSON.toJSONString(byUsername));
                    //如果用户在.没有离职
                    if (byUsername != null && byUsername.getDeleted().equals(0)) {
                        currentUser.login(token);
                        //返回给前端信息
                        Map<String,Object> userInfo=new HashMap<>();
                        userInfo.put("userId",byUsername.getId());
                        userInfo.put("username",byUsername.getUsername());
                        userInfo.put("name",byUsername.getName());
                        userInfo.put("roleId",byUsername.getRoleId());

                        response.addCookie(new Cookie("username",byUsername.getUsername()));
                        response.addCookie(new Cookie("name",byUsername.getName()));

                        return new Result(true,StatusCode.OK,"登录成功",userInfo);
                    }
                }
                boolean authenticated = currentUser.isAuthenticated();
                log.info("登陆状态>>>" + authenticated);

            } catch (AuthenticationException e) {
                System.out.println("登陆失败：" + e.getMessage());
                return new Result(false,StatusCode.ERROR,"登陆失败");
            }
        }
        return new Result(true,StatusCode.OK,"用户已经登录",username);
    }
    @PostMapping("/register")
    public Result register(@RequestBody String data){
        System.out.println("jsonStr>>" + data);
        JSONObject jsonObject = JSONObject.parseObject(data);
        String username =jsonObject.get("username").toString();
        String password = jsonObject.get("password").toString();
        String name =jsonObject.get("name").toString();
      //  String name = jsonObject.getString("name");
        log.info("进入注册接口>" + ",username>>" + username +",password>>" + ",name>" +name);
      /*  String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");*/
        log.info("入参解析:"+username + "密码：" + password + "真实名字：" + name );
        //非空校验
            if(data == null || StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(name)){
                return new Result(true,StatusCode.OK,"用户名，密码，真实姓名不能为空");
            }
            while(!checkName(username)) {
                return new Result(true,StatusCode.OK,"用户名：必须是6-10位字母、数字、下划线，不能以数字开头");
            }
            while(!checkPwd(password)) {
                return new Result(true,StatusCode.OK,"密码:必须是6-20位的字母、数字、下划线");
            }
            //防止重复注册
        User userDB = userService.findByUsername(username);
        //如果从数据库中可以找到。
            if (null != userDB ){
                log.info("用户名已经存在");
                return new Result(true,StatusCode.OK,"用户名已经存在");
            }
        User user = new User();
        user.setUsername(username);
        user.setName(name);
        String MD5PWD = new Md5Hash(password,username).toString();
        user.setPassword(MD5PWD);

        user.setLastLoginTime(LocalDateTime.now());
        user.setDeleted(0);
        user.setRoleId(2);
        userService.add(user);
            return new Result(true,StatusCode.OK,"注册成功");
        }
}